
package com.joysuch.wwyt.datadump.biz.convertor;

import java.lang.reflect.Array;
import java.util.Collection;
import java.util.Iterator;

import cn.zlg.common.datadump.annotation.DataDumpField;
import cn.zlg.common.datadump.convertor.FieldValueConvert;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

/**
 * 将 Array,Collection, Iterator, Iterable内容拼接成字符串
 * 
 */
@Component
public class JoinToStringConvertor implements FieldValueConvert<Object, String> {

    private String defaultConnector = ",";

    @Override
    public String convert(Object bean, Object value, DataDumpField dataField) {
        if (value == null) {
            return null;
        }
        String connector = dataField.exportConvertorParams().length > 0 ? dataField.exportConvertorParams()[0]
                : defaultConnector;
        if (value.getClass().isArray()) {
            StringBuilder sb = new StringBuilder();
            int length = Array.getLength(value);
            for (int i = 0; i < length; i++) {
                sb.append(Array.get(value, i));
                if (i != length - 1) {
                    sb.append(connector);
                }
            }
            return sb.toString();
        } else if (value instanceof Collection) {
            return StringUtils.join((Collection) value, connector);
        } else if (value instanceof Iterable) {
            return StringUtils.join((Iterable) value, connector);
        } else if (value instanceof Iterator) {
            return StringUtils.join((Iterator) value, connector);
        }
        throw new RuntimeException(value.getClass().getName() + " 不是支持的类型");
    }

}
